package cn.skylark.wcm.common.splitter.docx;

import cn.skylark.wcm.common.splitter.doc.Util;
import cn.skylark.wcm.common.util.Constants;
import org.zwobble.mammoth.DocumentConverter;
import org.zwobble.mammoth.Result;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class docxSplitter {
    /**
     * docx 的html拆分
     *
     * @param filename 文件地址
     * @param level    拆分级别
     * @return
     * @throws Throwable
     */
    public static String docxsplithtml(String filename, String level) throws Throwable {
        //大标题为<h1>可以考虑使用小标题拆分
        //有些文档不是用 <h1>分割，需要处理
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateFile = sdf.format(date);
        String titlemarkup = "<h[1-" + level + "]>";
        String html_header = "<html><head><meta http-equiv=\"content-type\" content=\"text/html\" charset=\"UTF-8\"/></head><body>";
        String html_footer = "</body></html>";
        String WITH_DELIMITER = "(?=%1$s)";

        File file = new File(filename);
        DocumentConverter converter = new DocumentConverter();
        Result<String> result = null;
        try {
            result = converter.convertToHtml(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //得到转换后的html。
        String html = result.getValue(); // The generated HTML
        String[] sections = html.split(String.format(WITH_DELIMITER, titlemarkup));
        //String[] sections=html.split(titlemarkup);
        //将docx分拆结果存放到同名目录
        int i = 0;
        String dir = Util.removedocextension(filename);
        String outPath = filename.substring(0, filename.lastIndexOf(".")) + "_"+dateFile;
        File newOutPathFile = new File(outPath);
        if (!newOutPathFile.exists()) {
            newOutPathFile.mkdirs();
        }

        for (i = 0; i < sections.length; i++) {
            String content = sections[i];
            //取<h1>...</h1>之间的部分
            String title = "";
            if (content.indexOf("</h") != -1) {
                int h_end = content.indexOf("</h");
                title = content.substring(4, h_end);
                //去除<h1>...</h1>之间的</a>之前的内容，后面就是章节标题，做为文件名。
                while (title.indexOf("<a") != -1) {
                    title = title.substring(0, title.indexOf("<a")) + title.substring(title.indexOf("</a>") + 4, title.length());
                }
            } else if (content.indexOf("<strong>") != -1) {
                title = content.substring(content.indexOf("<strong>") + 8, content.indexOf("</strong>"));
            } else {
                File file1 = new File(filename);
                String remoteName = file1.getName();
                title = remoteName.substring(0, remoteName.lastIndexOf("."));
            }

            if (title.length() != 0 && content != null) {
                //写html文件
                String oldname = Util.generateFilename(title);
                String name = oldname;
                String htmlpath = outPath + "/" + name + ".html";
                String oldContent = content.substring(0, content.lastIndexOf("<"));
                String newContent = oldContent.substring(oldContent.lastIndexOf(">") + 1);
                if (!newContent.equals(Util.generateFilename(title))) {
                    Util.writeFile(html_header + content + html_footer, htmlpath, false);
                }
            }
        }
        return dateFile;
    }

    /**
     * 进行docx的txt拆分。
     *
     * @param filename   文件的地址
     * @param level      文件的层次
     * @param remotepath 远端地址的路径
     * @param dateFile   时间戳
     * @throws Throwable
     */
    public static void docxsplitTxt(String filename, String level, String[] remotepath, String dateFile) throws Throwable {
        //写txt文件
        //原始文件名
        String titlemarkup = "<h[1-" + level + "]>";
        String WITH_DELIMITER = "(?=%1$s)";
        String html_header = "<html><head><meta http-equiv=\"content-type\" content=\"text/html\" charset=\"UTF-8\"/></head><body>";
        String html_footer = "</body></html>";
        File file = new File(filename);
        DocumentConverter converter = new DocumentConverter();
        Result<String> result = null;
        try {
            result = converter.convertToHtml(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String html = result.getValue(); // The generated HTML
        String[] sections = html.split(String.format(WITH_DELIMITER, titlemarkup));
        //将docx分拆结果存放到同名目录
        String dir = Util.removedocextension(filename);
        for (int i = 0; i < sections.length; i++) {
            String content = sections[i];
            //取<h1>...</h1>之间的部分
            String title = "";
            if (content.indexOf("</h") != -1) {
                int h_end = content.indexOf("</h");
                title = content.substring(4, h_end);
                //去除<h1>...</h1>之间的</a>之前的内容，后面就是章节标题，做为文件名。
                while (title.indexOf("<a") != -1) {
                    title = title.substring(0, title.indexOf("<a")) + title.substring(title.indexOf("</a>") + 4, title.length());
                }
            } else if (content.indexOf("<strong>") != -1) {
                title = content.substring(content.indexOf("<strong>") + 8, content.indexOf("</strong>"));
            } else {
                File file1 = new File(filename);
                String remoteName = file1.getName();
                title = remoteName.substring(0, remoteName.lastIndexOf("."));
            }
            String oldname = Util.generateFilename(title);
            String name = oldname;
            if (title.length() != 0 && content != null) {
                String oldContent = content.substring(0, content.lastIndexOf("<"));
                String newContent = oldContent.substring(oldContent.lastIndexOf(">") + 1);
                //c:/1/2/3.docx
                String fileName;
                String newRemotepath = "";
                if (!newContent.equals(Util.generateFilename(title))) {
                    //新建文件夹，加时间戳。
                    String filePath = filename.substring(0, filename.lastIndexOf(".")) + "_"+dateFile;
                    File folder = new File(filePath);
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }

                    for (int j = 0; j < remotepath.length; j++) {
                        fileName = remotepath[j].substring(remotepath[j].lastIndexOf(">") + 1);
                        if (fileName.equals(name.trim())) {
                            //http://publictest-1253363526.file.myqcloud.com/file/17813e16ded146a9872da22c246917b9.html>
                            newRemotepath = remotepath[j].substring(remotepath[j].lastIndexOf("/") + 1, remotepath[j].lastIndexOf(">"));
                        }
                    }
                    //得到所有的txt文件。
                    String cleanTxt = Util.html2text(html_header + content + html_footer);
                    String newTxt = "";
                    String[] split = cleanTxt.trim().split("。");
                    for (int x = 0; x < split.length; x++) {
                        if (x < split.length - 1) {
                            newTxt += split[x] + "。" + "\r\n";
                        } else {
                            newTxt += split[x] + "\r\n";
                        }
                    }
                    Util.writeFile(name.trim() + "\r\n" + Constants.SERVERPATH + "/" + "upload/html/" + newRemotepath + "\r\n" + newTxt, filePath + File.separator + name.trim() + ".txt", true);
                }
            }
        }
    }
}